package name.zxw.rabbitmq.exchange;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 消费者
 *
 * @author zhangxinwang
 * @date 2022/6/22 15:49
 */
public class MyConsumer2 {


    public static void main(String[] args) throws Exception {
        String exchangeName = "logs";

        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //交换机声明
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT);
        //队列声明
        //channel.queueDeclare()等效channel.queueDeclare("",false,true,true,null)
        //队列名不能为null,如果是空串"",在recordQueue方法中服务器命名参数会被置为true,即系统会自动给你起个名字
        String queueName = channel.queueDeclare().getQueue();
        //队列绑定
        channel.queueBind(queueName, exchangeName, "bbb");

        //Publisher

        System.out.println("等待接收消息...");
        channel.basicConsume(queueName, false,
                (consumerTag, message) -> {
                    System.out.println("consumer2,传递回调:");
                    System.out.println("consumerTag = " + consumerTag);
                    System.out.println("new String(message.getBody()) = " + new String(message.getBody()));
                    channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                },
                (consumerTag) -> {
                    System.out.println("consumer2,取消回调");
                    System.out.println("consumerTag = " + consumerTag);
                }
        );


    }


}
